<template>
  <div class="metronome-container">
    <loading :active.sync="isLoading"
             :can-cancel="true"
             :color="loadingIconColor"
             :lock-scroll="true"
             :loader="loadingIcon"
             :height=100
             :width=100
             :on-cancel="onCancel"
             :is-full-page="fullPageLoading"/>
    <div class="metronome-frame">
      <div class="metronome-left">
        <div v-for="(item,index) in data" :key="index" class="metronome-left-item"
             @click="selectData(item)">
          <div class="metronome-left-item-imgdiv"
               :class="item.img==selectItem.img?'metronome-left-item-imgdiv imgselect':'metronome-left-item-imgdiv '">
            <img :src="onPreView(item)" :width="item.resizewidth"
                 :height="item.resizeheight"/>
            <p class="filename" :title="item.img" v-if="index!=data.length">{{ item.img }}</p>
            <div class="ocr-status" v-if="index!=data.length">
              <i v-if="item.ocrState==0&&!item.loading" class="iconfont icon-daiban ocr-status-no-icon">待识别</i>
              <i v-else-if="item.ocrState==0&&item.loading" class="iconfont icon-saomiaoshibie ocr-status-ocr-icon">识别中</i>
              <i v-else-if="item.ocrState==1" class="iconfont icon-chenggong ocr-status-success-icon">识别成功</i>
              <i v-else-if="item.ocrState==-1" class="iconfont icon-shibai ocr-status-fail-icon">识别失败</i>
              <i v-else-if="item.ocrState==2" class="iconfont icon-shangchuanzhong ocr-status-upload-icon">上传中</i>
            </div>
            <div class="wrapper" v-if="item.loading"></div>
            <div class="greenwrapper" v-if="item.ocrState==2"></div>
          </div>
        </div>
        <div class="metronome-left-item"
             @click="selectData(pzimg)">
          <div class="metronome-left-item-imgdiv"
               :class="pzimg.img==selectItem.img?'metronome-left-item-imgdiv imgselect':'metronome-left-item-imgdiv '">
            <img :src="pzimg.img"/>
          </div>
        </div>
      </div>
      <div class="metronome-content">
        <div class="metronome-content-head" style="justify-content: space-between;">
          <template v-if="!flag">
            <div class="metronome-content-head-item"
                 :class="{'disabled': selectItem.img==''||selectItem.isshowocrresult||selectItem.ocrState==2||selectItem.loading}">
              <div class="bth-circle" @click="rotate(-90)">
                <i class="iconfont icon-refresh"></i>
              </div>
            </div>
            <div class="metronome-content-head-item">
              <div class="common-btn" @click="rectify"
                   :class="{'disabled': selectItem.img==''||selectItem.isshowocrresult||selectItem.ocrState==2||selectItem.loading}">
                <i class="iconfont icon-sousuo">纠偏</i>&nbsp;
              </div>
            </div>
            <div class="metronome-content-head-item">
              <div class="common-btn" @click="enhanceContrast"
                   :class="{'disabled': selectItem.img==''||selectItem.isshowocrresult||selectItem.ocrState==2||selectItem.loading}">
                <i class="iconfont icon-duibidu">对比度</i>
              </div>
            </div>
            <div class="metronome-content-head-item">
              <div :class="{'disabled':(selectItem.img==''||selectItem.isshowocrresult||selectItem.ocrState==2||selectItem.loading)}" class="common-btn"
                   @click="pictureorc()">
                <i class="iconfont icon-OCRshibie">识别</i>
              </div>
            </div>
            <div class="metronome-content-head-item">
              <div :class="{'disabled':(selectItem.img=='')}" class="common-btn" @click="showresult()">
                <i class="iconfont icon-zitiyulan">{{ selectItem.isshowocrresult ? '预览' : '查看' }}</i>
              </div>
            </div>
            <div class="metronome-content-head-item"
                 :class="{'disabled': selectItem.img==''||selectItem.isshowocrresult||selectItem.ocrState==2||selectItem.loading}">
              <div class="bth-circle" @click="rotate(90)">
                <i class="iconfont icon-icon_refresh"></i>
              </div>
            </div>
          </template>
          <template v-else>
            <div class="metronome-content-head-item">
              <div class="common-btn" @click="cameraLeftRotate">
                <i class="iconfont icon-refresh">左旋转</i>
              </div>
            </div>
            <div class="metronome-content-head-item">
              摄像头：
              <select @change="(event)=>{this.getStream()}" v-model="videoSelect" class="select">
                <option v-for="(item,index) in options" :value="item.value" :key="index">{{ item.label }}</option>
              </select>
            </div>
            <div class="metronome-content-head-item">
              清晰度:
              <select v-model="qxdSelect" class="select">
                <option v-for="(item,index) in qxdlist" :value="item.item" :key="index">{{ item.label }}</option>
              </select>
            </div>
            <div class="metronome-content-head-item">
              <div class="common-btn"
                   @click="downloadfile">
                <i class="iconfont icon-wenjianxiazai">下载素材</i>
              </div>
            </div>
            <div class="metronome-content-head-item">
              <div class="common-btn" @click="cameraRightRotate">
                <i class="iconfont icon-icon_refresh">右旋转</i>
              </div>
            </div>
          </template>
        </div>
        <div class="metronome-content-show">
          <div v-show="!flag" class="metronome-content-img" id="metronome-content-img">
            <template v-if="selectItem.img!=''&&selectItem.img!=pz" >
            <viewer :images="preViewImage"  class="viewer" :options="viewoptions">
              <img ref="metronome-content-img" @click="preView" :class="selectItem.isshowocrresult?'noneimg':'showimg'"
                   @load="resizeImg($event)" :src="onPreView(selectItem)">
            </viewer>
            </template>
            <div v-else class="empty">暂无选中的图片</div>
            <div v-if="selectItem.isshowocrresult" class="metronome-content-img-desc">
              <div v-for="(item,index) in selectItem.res" :key="index"
                   :style="'position:absolute;left:' + item.box[0]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth) /$refs['metronome-content-img'].width * 100
                    + '%;top:' + item.box[1]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth) /$refs['metronome-content-img'].height * 100 + '%;border: 1px solid #ccc;width:' + (item.box[2]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth) - item.box[0]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth)) * ($refs['metronome-content-img'].width / $refs['metronome-content-img'].width)
                    + 'px;height:' + ((item.box[7]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth) - item.box[1]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth)) * ($refs['metronome-content-img'].width / $refs['metronome-content-img'].width) + 2) + 'px;'">
                <div :style=" ((item.box[7]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth) - item.box[1]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth)) * ($refs['metronome-content-img'].width / $refs['metronome-content-img'].width)-1)<12?
              ('font-family:宋体;line-height:' + ((item.box[7]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth) - item.box[1]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth)) * ($refs['metronome-content-img'].width / $refs['metronome-content-img'].width)-1) + 'px;font-size:0.8em;'):
              ('font-family:宋体;line-height:' + ((item.box[7]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth) - item.box[1]*($refs['metronome-content-img'].width/$refs['metronome-content-img'].naturalWidth)) * ($refs['metronome-content-img'].width/ $refs['metronome-content-img'].width)-1) + 'px;font-size:1em;')"
                     class="ocrlinesmallfont">{{ item.text }}
                </div>
              </div>
            </div>
            <div class="greenwrapper" v-if="selectItem.ocrState==2"></div>
            <div class="wrapper" v-if="selectItem.loading"></div>
          </div>
          <div v-show="flag" class="metronome-content-photograph" ref="metronome-content-photograph"
               v-resize="handleResize">
            <video id="video" ref="metronome-video" autoplay crossOrigin='Anonymous'
                   style="transform:rotate(90deg);"></video>
            <i class="iconfont icon-paizhao- pzicon" :class="{'disabled':streamCopy==null}" @click="takePhoto"></i>
          </div>
        </div>
      </div>
      <div style="clear: both"></div>
    </div>
  </div>
</template>

<script>
import "./../assets/js/viewer";
import "./../assets/js/resize";
import Loading from 'vue-loading-overlay';
import 'vue-loading-overlay/dist/vue-loading.css';

export default {
  name: "IbzOcrCamera",
  props: {
    ocrroot: {
      type: String,
      default: function () {
        return "ocr/ocrrecord";//ocr识别地址
      }
    },
    websockocrurl: {
      type: String,
      default: function () {
        return "";//ocr识别地址
      }
    },
    loadingIcon:{
      type: String,
      default: function () {
        return "bars";//加载动画图标spinner or dots or bars
      }
    },
    loadingIconColor:{
      type: String,
      default: function () {
        return "#296BEF";//加载动画颜色
      }
    },
    fullPageLoading:{
      type: Boolean,
      default: function () {
        return false;//加载动画是否全屏
      }
    },
    ocrrecordid: {
      type: String,
    },
    model: {
      type: Boolean,
      default: function () {
        return true;//默认拍摄模式
      }
    },
  },
  created() {
    if (this.ocrrecordid != undefined) {
      this.ocrid = this.ocrrecordid;
    } else {
      this.ocrid = this.createUUID();
    }
    this.flag = this.model

    this.pzimg.img = this.pz;
    this.loadData();
    if (this.model) {
      this.selectData(this.pzimg);
    } else {
      if (this.data.length > 0) {
        this.selectItem = this.data[0];
      }
    }
  },
  data() {
    return {
      // eslint-disable-next-line vue/no-dupe-keys
      data: [],
      selectItem: {
        "img": "",
        "base64": "",
        "content": "",
        "height": "",
        "ocrState": "",
        "oldbase64": "",
        "oldheight": "",
        "loading": "",
        "oldwidth": "",
        "res": "",
        "isshowocrresult": "",
        "timetake": "",
        "title": "",
        "width": "",
        "createdate": ""
      },
      viewoptions:{
      Options: {
        'inline': true, // 是否启用inline模式
            'button': true, // 是否显示右上角关闭按钮
            'navbar': true, // 是否显示缩略图底部导航栏
            'title': true, // 是否显示当前图片标题，默认显示alt属性内容和尺寸
            'toolbar': false, // 是否显示工具栏
            'tooltip': true, // 放大或缩小图片时，是否显示缩放百分比，默认true
            'fullscreen': true, // 播放时是否全屏，默认true
            'loading': true, // 加载图片时是否显示loading图标，默认true
            'loop': false, // 是否可以循环查看图片，默认true
            'movable': true, // 是否可以拖得图片，默认true
            'zoomable': true, // 是否可以缩放图片，默认true
            'rotatable': true, // 是否可以旋转图片，默认true
            'scalable': true, // 是否可以翻转图片，默认true
            'toggleOnDblclick': true, // 放大或缩小图片时，是否可以双击还原，默认true
            'transition': false, // 使用 CSS3 过度，默认true
            'keyboard': true, // 是否支持键盘，默认true
            'zoomRatio': 0.1, // 鼠标滚动时的缩放比例，默认0.1
            'minZoomRatio': 0.01, // 最小缩放比例，默认0.01
            'maxZoomRatio': 100, // 最大缩放比例，默认100
            'url': 'data-source' // 设置大图片的 url
      }
    },
      isLoading: false,
      flag: false,
      streamCopy: null,
      fullPage: false,
      qxdlist: [
        {
          "label": "高清",

          "item": {
            "height": 1428,
            "width": 1000,
          }
        },
        {
          "label": "普通",
          "item": {
            "height": 1142,
            "width": 800,
          }
        },
        {
          "label": "标清",
          "item": {
            "height": 800,
            "width": 560,
          }
        }
      ],
      rotateDeg: 90,
      options: [],
      videoSelect: "",
      qxdSelect: {
        "height": 1142,
        "width": 800,
      },
      preViewImage: [],
      pzimg: {"img": "", "flag": true,"loading":false},
      ocrid: "",
      pz: "",
      empty: "",
    }

  },
  components: {

    Loading
  },
  methods: {
    handleResize({width, height}) {
      if (width != undefined && height != undefined && this.$refs["metronome-video"] != undefined) {
        if (height != "" && width != "")
          height = parseInt(height.replace("px", ""))
        width = parseInt(width.replace("px", ""))
        this.$refs["metronome-video"].height = this.$refs["metronome-video"].width = height > width ? width : height
      }
    },
    /**
     * 预览图片
     */
    onPreView(item) {
      if (item.img == "") {
        return this.empty;
      } else {
        return "data:image/" + item.img.substring(item.img.indexOf("."), item.img.length) + ";base64," + item.base64;
      }
    },
    preView() {
      this.preViewImage = ["data:image/" + this.selectItem.img.substring(this.selectItem.img.indexOf("."), this.selectItem.img.length) + ";base64," + this.selectItem.base64];
    },
    /**
     * 获取数据
     */
    loadData() {
      this.isLoading = true;
      var xml = new XMLHttpRequest();
      xml.open('GET', this.ocrroot + "/" + this.ocrid, true) // 第三个值指定接口是否异步
      xml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      xml.onload = (e) => {
        // 获取到接口调用成功后的返回数据
        const res = JSON.parse(e.currentTarget.response);
        this.data = res.imgItems;
        for (let i = 0; i < this.data.length; i++) {
          var resizeLeftImg = this.resizeLeftImg(this.data[i]);
          this.$set(this.data[i], "loading", false);
          this.$set(this.data[i], "resizeheigt", resizeLeftImg.height);
          this.$set(this.data[i], "resizewidth", resizeLeftImg.width);
        }
        this.isLoading = false;
        setTimeout(() => {
          this.scrollIntoView()
        }, 100)
      }
      xml.onerror = (e) => {
        this.isLoading = false;
        e.preventDefault()
      }
      xml.send();
    },
    /**
     * 选择侧边栏处理
     * @param item
     * @returns {Promise<void>}
     */
    async selectData(item) {
      this.selectItem = item
      this.$set(this.selectItem, "isshowocrresult", false)//设置识别结果默认值
      //清空识别结果样式
      this.flag = item.flag == undefined ? false : true
      debugger
      if (item.flag&&this.videoSelect=="") {
        await navigator.mediaDevices.enumerateDevices().then(this.gotDevices).then(this.getStream).catch(this.handleError);
        var height = this.$refs["metronome-content-photograph"].clientHeight;
        var width = this.$refs["metronome-content-photograph"].clientWidth;
        this.$refs["metronome-video"].height = this.$refs["metronome-video"].width = height > width ? width : height
      }
    },
    gotDevices(deviceInfos) {
        this.options = [];
        for (var i = 0; i < deviceInfos.length; ++i) {
          var deviceInfo = deviceInfos[i];
          if (deviceInfo.kind === 'videoinput') {
            if (deviceInfo.label.startsWith("Integrated ")) {
              console.log("hello worlld")
            } else {
              if (deviceInfo.label.startsWith("ZMFZL")) {
                this.videoSelect = deviceInfo.deviceId;
              }
              var option = {};
              option.label = deviceInfo.label;
              option.value = deviceInfo.deviceId;
              this.options.push(option);
            }
          }
        }
    },
    getStream() {
      this.closeCamera();
      const constraints = {
        video: {width: {exact: 1440}, height: {exact: 1080}, deviceId: this.videoSelect}
      };
      navigator.mediaDevices.getUserMedia(constraints).then(this.gotStream).catch(this.handleError);
    },
    gotStream(stream) {
      this.streamCopy = stream; // make stream available to console
      var videoSource = this.$refs["metronome-video"];
      videoSource.srcObject = stream;
    },
    closeCamera() {
      if (this.streamCopy != null && this.streamCopy != undefined && this.streamCopy != '') {
        try {
          this.streamCopy.stop(); // if this method doesn't exist, the catch will be executed.
        } catch (e) {
          this.streamCopy.getVideoTracks()[0].stop(); // then stop the first video track of the stream
        }
      }
    },
    base64ToFile(base64Data, fileName) {
      let arr = base64Data.split(','),
          fileType = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]),
          l = bstr.length,
          u8Arr = new Uint8Array(l);
      while (l--) {
        u8Arr[l] = bstr.charCodeAt(l);
      }
      return new File([u8Arr], fileName, {type: fileType});
    },

    formatTime(time, fmt) {
      if (!time) return ''
      else {
        const date = new Date(time)
        const o = {
          'M+': date.getMonth() + 1,
          'd+': date.getDate(),
          'H+': date.getHours(),
          'm+': date.getMinutes(),
          's+': date.getSeconds(),
          'q+': Math.floor((date.getMonth() + 3) / 3),
          S: date.getMilliseconds()
        }
        if (/(y+)/.test(fmt)) {
          fmt = fmt.replace(
              RegExp.$1,
              (date.getFullYear() + '').substr(4 - RegExp.$1.length)
          )
        }
        for (const k in o) {
          if (new RegExp('(' + k + ')').test(fmt)) {
            fmt = fmt.replace(
                RegExp.$1,
                RegExp.$1.length === 1
                    ? o[k]
                    : ('00' + o[k]).substr(('' + o[k]).length)
            )
          }
        }

        return fmt
      }
    },
    /**
     * 拍照图片
     */
    takePhoto() {
      var videoSource = this.$refs["metronome-video"];
      var height = this.qxdSelect.width;
      var width = this.qxdSelect.height;
      let c = document.createElement("canvas");
      let context2d = c.getContext("2d");
      var degree = this.rotateDeg % 360;
      // eslint-disable-next-line no-compare-neg-zero
      if (degree == 0 || degree == -0) {
        c.height = height;
        c.width = width;
        context2d.translate(0, 0);
      } else if (degree == 90 || degree == -270) {
        c.height = width;
        c.width = height;
        context2d.translate(height, 0);
      } else if (degree == 180 || degree == -180) {
        c.height = height;
        c.width = width;
        context2d.translate(width, height);
      } else if (degree == 270 || degree == -90) {
        c.height = width;
        c.width = height;
        context2d.translate(0, width);
      }
      context2d.rotate(degree * Math.PI / 180);
      context2d.drawImage(videoSource, 0, 0, width, height)
      var url = c.toDataURL("image/jpeg", 9);
      let file = this.base64ToFile(url);
      // 获取时间，准备当做文件名
      let time = this.formatTime(new Date(), "yyyy-MM-dd HH-mm-ss");
      let filename = time + "-" + this.s4() + ".jpeg";
      let renameFile = new File([file], filename, {type: "image/jpeg"})
      var formData = new FormData();
      formData.append('file', renameFile);
      //接口预处理
      var preitems = {
        "resizeheigt": "",
        "resizewidth": "",
        "img": filename,
        "ocrState": 2,
        "base64": url.split(',')[1],
        "loading": false,
        "height": c.height,
        "width": c.width,
      };
      var resizeLeftImg = this.resizeLeftImg(preitems);
      this.$set(preitems, "loading", false);
      this.$set(preitems, "resizeheigt", resizeLeftImg.height);
      this.$set(preitems, "resizewidth", resizeLeftImg.width);
      this.data.push(preitems)
      this.$forceUpdate()
      this.scrollIntoView()
      var xml = new XMLHttpRequest();
      xml.open('POST', this.ocrroot + "/" + this.ocrid + "/upload", true) // 第三个值指定接口是否异步
      // 接口调用成功回调
      xml.onload = (e) => {
        // 获取到接口调用成功后的返回数据
        const res = JSON.parse(e.currentTarget.response);
        for (let i = 0; i < res.length; i++) {
          this.datachange(res[i])
          this.singleOcr2({ocrrecordid: this.ocrid, img: res[i].img, loading: true})
        }
      }
      // 接口调用失败处理
      xml.onerror = (e) => {
        // 接口调用失败后的处理
        this.isLoading = false;
        console.log(e)
      }
      xml.send(formData)

    },

    /**
     * 左旋转90
     */
    cameraLeftRotate() {
      this.rotateDeg -= 90;
      var videoSource = this.$refs["metronome-video"];
      videoSource.style.transform = "rotate(" + this.rotateDeg + "deg)";
    },
    onCancel() {
      console.log('User cancelled the loader.')
    },
    /**
     * 右旋转90
     */
    cameraRightRotate() {
      this.rotateDeg += 90;
      var videoSource = this.$refs["metronome-video"];
      videoSource.style.transform = "rotate(" + this.rotateDeg + "deg)";
    },
    singleOcr2(params) {
      if (this.websockocrurl != undefined && this.websockocrurl != '') {
        this.websockocr(params);
      } else {
        this.httpocr(params)
      }
    },
    s4() {
      return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1);
    },
    createUUID() {
      return this.s4() + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' + this.s4() + '-' + this.s4() + this.s4() + this.s4();
    },
    websockocr(params) {
      let socket = new WebSocket(this.websockocrurl);
      this.datachange(params)
      socket.onopen = () => {
        console.log("连接成功!");
        socket.send(JSON.stringify(params));
      }
      socket.onmessage = ($event) => {
        let data = JSON.parse($event.data);
        this.datachange(data)
        socket.close();
      }
      socket.onclose = () => {
        console.log("连接断开");
      }
    },
    httpocr(params) {
      var xml = new XMLHttpRequest();
      this.datachange(params)
      let param = {"img": params.img}
      xml.open('POST', this.ocrroot + "/" + this.ocrid + "/orcimg", true) // 第三个值指定接口是否异步
      xml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      xml.onload = (e) => {
        // 获取到接口调用成功后的返回数据
        const res = JSON.parse(e.currentTarget.response);
        this.datachange(res)
      }
      xml.send(JSON.stringify(param))
    },
    scrollIntoView() {
      this.$nextTick(() => {
        this.$el.querySelector(`.metronome-left-item:last-child`).scrollIntoView({
          behavior: "smooth",
          block: 'center'
        })
      });
    },
    /**
     * ocr图片识别
     */
    pictureorc() {
      this.singleOcr2({ocrrecordid: this.ocrid, img: this.selectItem.img, loading: true});
    },
    downloadfile() {
      this.isLoading = true;
      let url = this.ocrroot + "/" + 'ocrFile/previewPDF/' + this.ocrid;
      let oReq = new XMLHttpRequest();
      oReq.open("GET", url, true);
      oReq.responseType = "blob";
      oReq.setRequestHeader("Content-Type", "application/json");
      oReq.onload = () => {
        let content = oReq.response;
        let elink = document.createElement("a");
        elink.download = "识别列表" + this.ocrid + ".pdf";
        elink.style.display = "none";
        let blob = new Blob([content]);
        elink.href = URL.createObjectURL(blob);
        document.body.appendChild(elink);
        elink.click();
        document.body.removeChild(elink);
        this.isLoading = false;
      };
      oReq.onerror = () => {
        this.isLoading = false;
      }
      oReq.send()
    },

    showresult() {
      this.$set(this.selectItem, "isshowocrresult", !this.selectItem.isshowocrresult)
    },
    /**
     * 增强对比度
     */
    enhanceContrast() {
      this.isLoading = true;
      let param = {img: this.selectItem.img};
      var xml = new XMLHttpRequest();

      xml.open('POST', this.ocrroot + "/" + this.ocrid + "/normalizeimg", true) // 第三个值指定接口是否异步
      xml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      xml.onload = (e) => {
        // 获取到接口调用成功后的返回数据
        const res = JSON.parse(e.currentTarget.response);
        this.datachange(res)
        this.isLoading = false;
      }
      xml.onerror = () => {
        this.isLoading = false;
      }
      xml.send(JSON.stringify(param))
    },
    resizeImg(ev) {

      var img = ev.target;
      var width;
      var height;
      if (img.naturalHeight > img.naturalWidth) {
        height = this.qxdlist[1].item.height
        width = this.qxdlist[1].item.width
      } else {
        height = this.qxdlist[1].item.width
        width = this.qxdlist[1].item.height
      }
      img.height = height
      img.width = width;
      document.getElementById("metronome-content-img").style.height = height + "px"
      document.getElementById("metronome-content-img").style.width = width + "px"
    },
    resizeLeftImg(ev) {
      debugger
      var height = document.getElementsByClassName("metronome-left-item-imgdiv")[0].getBoundingClientRect().height - 40;
      var width = document.getElementsByClassName("metronome-left-item-imgdiv")[0].getBoundingClientRect().width - 20;
      var imgwidth = ev.width;
      var imgheight = ev.height;

      if (imgheight == undefined && imgwidth == undefined) {
        return;
      }
      var scalebox = width / height;
      var scaleImg = imgwidth / imgheight;
      if (scalebox > scaleImg) {
        if (height < imgheight) {
          imgheight = height;
          imgwidth = height * scaleImg;
        } else {
          while (height > imgheight && width > imgwidth) {
            let tempheight = imgheight;
            let tempwidth = imgwidth;
            tempheight = tempheight * 1.1;
            tempwidth = tempheight * scaleImg;
            if (tempheight < height && tempwidth < width) {
              imgwidth = tempwidth;
              imgheight = tempheight;
            } else {
              break;
            }
          }
        }

      } else {
        if (width < imgwidth) {
          imgwidth = width;
          imgheight = width / scaleImg;
        } else {
          while (height > imgheight && width > imgwidth) {
            let tempheight = imgheight;
            let tempwidth = imgwidth;
            tempheight = tempheight * 1.1;
            tempwidth = tempheight * scaleImg;
            if (tempheight < height && tempwidth < width) {
              imgwidth = tempwidth;
              imgheight = tempheight;
            } else {
              break;
            }
          }
        }
      }
      return {"height": imgheight, "width": imgwidth};

    },

    /**
     * 图片旋转
     * @param e
     */
    rotate(deg) {
      this.isLoading = true;
      let param = {img: this.selectItem.img};
      var xml = new XMLHttpRequest();
      xml.open('POST', this.ocrroot + "/" + this.ocrid + "/rotateimg/" + deg, true) // 第三个值指定接口是否异步
      xml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      xml.onload = (e) => {
        // 获取到接口调用成功后的返回数据
        const res = JSON.parse(e.currentTarget.response);
        this.datachange(res)
        this.$forceUpdate();
        this.isLoading = false;
      }
      xml.onerror = () => {
        this.isLoading = false;
      }
      xml.send(JSON.stringify(param))

    },
    /**
     *纠偏
     */
    rectify() {
      this.isLoading = true;
      let param = {img: this.selectItem.img};
      var xml = new XMLHttpRequest();
      xml.open('POST', this.ocrroot + "/" + this.ocrid + "/deskewimg", true) // 第三个值指定接口是否异步
      xml.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
      xml.onload = (e) => {
        // 获取到接口调用成功后的返回数据
        const res = JSON.parse(e.currentTarget.response);
        this.datachange(res)
        this.isLoading = false;
      }
      xml.onerror = () => {
        this.isLoading = false;
      }
      xml.send(JSON.stringify(param))
    },
    datachange(data) {
      let store = 0;
      this.data.forEach((item, index) => {
        if (Object.is(item.img, data.img)) {
          store = index;
        }
      });
      this.data[store].loading = data.loading ? data.loading : false;
      if (data.loading) {//如果
        return;
      }
      this.data[store].ocrState = data.ocrState;
      if (data.ocrState == -1) {
        return;
      }
      this.data[store].content = data.content;
      this.data[store].res = data.res;
      if (data.base64 != undefined && this.data[store].base64 != data.base64) {
        this.data[store].base64 = data.base64
        if (data.height != undefined ) {
          this.data[store].height = data.height
        }
        if (data.width != undefined ) {
          this.data[store].width = data.width
        }
        var resizeLeftImg1 = this.resizeLeftImg(data);
      }
      if (resizeLeftImg1 != undefined) {
        this.data[store].resizewidth = resizeLeftImg1.width;
        this.data[store].resizeheight = resizeLeftImg1.height;
      }
    }
  },

}
</script>

<style scoped>
.metronome-container {
  margin: auto;
  padding: 20px;
  position: relative;
  height: 100%;
  width: 100%;
  box-sizing: border-box;
  background-color: white;
  min-width: 920px;
  min-height: 400px;
}

.metronome-frame {
  padding: 20px;
  margin: auto;
  border: 1px solid #eeeeee;
  position: absolute;
  top: 0px;
  bottom: 0px;
  left: 0px;
  right: 0px;
}

.metronome-frame .metronome-left {
  float: left;
  width: 200px;
  height: 100%;
  background-color: white;
  padding: 0px 20px 0px 0px;
  overflow-y: auto;
  overflow-x: hidden;
  box-sizing: border-box;
}

.metronome-frame .metronome-left .metronome-left-item {
  border-radius: 8px;
  padding: 20px 0px 20px 0px;
  position: relative;

}

.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv {
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  border-radius: 8px;
  padding: 10px;
  position: relative;
  min-width: 150px;
  height: 120px;
  text-align: center

}

.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv:hover {
  cursor: pointer;
}

.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv .filename {
  text-align: center;
  padding: 0px 24%;
  margin: 0px;
  white-space: nowrap;
  text-overflow: ellipsis;
  overflow: hidden;
  height: 20px;
}


.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv div.wrapper {
  width: 100%;
  height: 100%;
  background: linear-gradient(#1a98ca, #1a98ca),
  linear-gradient(90deg, #ffffff33 1px, transparent 0, transparent 19px),
  linear-gradient(#ffffff33 1px, transparent 0, transparent 19px),
  linear-gradient(transparent, #1a98ca);
  background-size: 100% 1.5%, 10% 100%, 100% 8%, 100% 100%;
  background-repeat: no-repeat, repeat, repeat, no-repeat;
  background-position: 0% 0%, 0 0, 0 0, 0 0;
  /* 初始位置 */
  clip-path: polygon(0% 0%, 100% 0%, 100% 1.5%, 0% 1.5%);
  /* 添加动画效果 */
  animation: move 2s infinite linear;
  position: absolute;
  top: 0px;
  left: 0px;
}
.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv div.greenwrapper {
  width: 100%;
  height: 100%;
  background: linear-gradient(#1aca3d, #6fca1a),
  linear-gradient(90deg, #ffffff33 1px, transparent 0, transparent 19px),
  linear-gradient(#ffffff33 1px, transparent 0, transparent 19px),
  linear-gradient(transparent, #49d412);
  background-size: 100% 1.5%, 10% 100%, 100% 8%, 100% 100%;
  background-repeat: no-repeat, repeat, repeat, no-repeat;
  background-position: 0% 0%, 0 0, 0 0, 0 0;
  /* 初始位置 */
  clip-path: polygon(0% 0%, 100% 0%, 100% 1.5%, 0% 1.5%);
  /* 添加动画效果 */
  animation: move 2s infinite linear;
  position: absolute;
  bottom: 0px;
  left: 0px;
}

@keyframes move {
  to {
    background-position: 0 100%, 0 0, 0 0, 0 0;
    /* 终止位置 */
    clip-path: polygon(0% 0%, 100% 0%, 100% 100%, 0% 100%);
  }
}

.metronome-frame .metronome-left .imgselect {
  border: 2px solid red;
}

.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv img {


}

.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv img:last-child {
  height: 100%;
  width: 100%;
}


.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv .ocr-status-no-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  color: orange;
}

.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv .ocr-status-fail-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  color: #E84335;
}

.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv .ocr-status-success-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  color: #1afa29;
}
.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv .ocr-status-ocr-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  color: #1ad1fa;
}

.metronome-frame .metronome-left .metronome-left-item .metronome-left-item-imgdiv .ocr-status-upload-icon {
  position: absolute;
  top: 20px;
  right: 20px;
  color: #40f6e7;
}

.metronome-frame .metronome-content {
  float: right;
  width: calc(100% - 200px);
  background-color: white;
  padding: 20px 0px 0px 0px;
  box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
  box-sizing: border-box;
  height: 100%;
}

.metronome-frame .metronome-content .metronome-content-head {
  height: 50px;
  border: 1px solid #F5F7F9;
  display: flex;
  box-sizing: border-box;
  padding: 8px;
}

.metronome-frame .metronome-content .metronome-content-head:last-child {
  border: none;
}


.metronome-frame .metronome-content .metronome-content-head-item {
  flex: 1;
  border-right: 1px solid #ebebeb;
  text-align: center

}

.metronome-frame .metronome-content .metronome-content-head-item:last-child {
  flex: 1;
  border-right: 0px solid #ebebeb;
  text-align: center

}

.metronome-frame .metronome-content .metronome-content-show {
  height: calc(100% - 90px);
  padding: 20px;
  overflow: scroll;
}

.metronome-frame .metronome-content .metronome-content-show .metronome-content-img {
  height: 100%;
  vertical-align: middle;
  /* 水平居中 */
  text-align: center;
  width: 100%;
  position: relative;
  margin: auto;
}

.metronome-frame .metronome-content .metronome-content-show .empty {
  font-size: x-large;
  vertical-align: middle;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%
}

.metronome-frame .metronome-content .metronome-content-show .metronome-content-img-desc {
  text-align: center;
  position: absolute;
  color: black;
  left: 0px;
  top: 0px;
  right: 0px;
  opacity: 1;
  bottom: 0px;
  font-size: 12px;
  background-color: #b1adad4a;
}

.metronome-frame .metronome-content .metronome-content-img-none {
  text-align: center;
  position: absolute;
  font-weight: bold;
  color: black;
  left: 0px;
  top: 0px;
  opacity: 0;
}

.metronome-frame .metronome-content .metronome-content-show .metronome-content-img div.wrapper {
  width: 100%;
  height: 100%;
  background: linear-gradient(#1a98ca, #1a98ca),
  linear-gradient(90deg, #ffffff33 1px, transparent 0, transparent 19px),
  linear-gradient(#ffffff33 1px, transparent 0, transparent 19px),
  linear-gradient(transparent, #1a98ca);
  background-size: 100% 1.5%, 10% 100%, 100% 8%, 100% 100%;
  background-repeat: no-repeat, repeat, repeat, no-repeat;
  background-position: 0% 0%, 0 0, 0 0, 0 0;
  /* 初始位置 */
  clip-path: polygon(0% 0%, 100% 0%, 100% 1.5%, 0% 1.5%);
  /* 添加动画效果 */
  animation: move 2s infinite linear;
  position: absolute;
  top: 0px;
  left: 0px;
}
.metronome-frame .metronome-content .metronome-content-show .metronome-content-img div.greenwrapper {
  width: 100%;
  height: 100%;
  background: linear-gradient(#1aca3d, #6fca1a),
  linear-gradient(90deg, #ffffff33 1px, transparent 0, transparent 19px),
  linear-gradient(#ffffff33 1px, transparent 0, transparent 19px),
  linear-gradient(transparent, #49d412);
  background-size: 100% 1.5%, 10% 100%, 100% 8%, 100% 100%;
  background-repeat: no-repeat, repeat, repeat, no-repeat;
  background-position: 0% 0%, 0 0, 0 0, 0 0;
  /* 初始位置 */
  clip-path: polygon(0% 0%, 100% 0%, 100% 1.5%, 0% 1.5%);
  /* 添加动画效果 */
  animation: move 2s infinite linear;
  position: absolute;
  bottom: 0px;
  left: 0px;
}
.metronome-frame .metronome-content .metronome-content-show .metronome-content-photograph {
  width: 100%;
  height: 100%;
  text-align: center;
  position: relative;
  background-color: black;
}

.metronome-frame .metronome-content .metronome-content-show .metronome-content-photograph .pzicon {
  font-size: 100px;
  position: absolute;
  bottom: 20px;
  left: 50%;
  color: white;
  margin-left: -50px;
}

.metronome-frame .metronome-content .metronome-content-show .metronome-content-photograph .pzicon:hover {
  opacity: 0.9;
  cursor: pointer;
}

.metronome-frame .metronome-content .metronome-content-show .metronome-content-img img {

  opacity: 1;
  margin: auto;

}

.metronome-frame .metronome-content .metronome-content-show .metronome-content-img .showimg {
  opacity: 1;

}

.metronome-frame .metronome-content .metronome-content-show .metronome-content-img .noneimg {
  height: 100%;
  width: 100%;
  opacity: 0;

}


.bth-circle {
  border-radius: 50%;
  display: inline-block;
  margin: auto;
  border: 1px solid #dcdfe6;
  padding: 5px;
  text-align: center;
  color: #606266;
  font-weight: 500;
  line-height: 1;
  transition: .1s;
  font-weight: 500;
}

.bth-circle:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
  cursor: pointer;
}

.common-btn {
  margin: auto;
  border: 1px solid #dcdfe6;
  padding: 5px;
  display: inline-block;
  text-align: center;
  border-radius: 3px;
  color: #606266;
  line-height: 1;
  transition: .1s;
  font-weight: 500;
}

.common-btn:hover {
  color: #409eff;
  border-color: #c6e2ff;
  background-color: #ecf5ff;
  cursor: pointer;

}

.ocrlinesmallfont {
  white-space: nowrap;
  /* autoprefixer           : off */
  -webkit-transform-origin-x: 0;
  /* autoprefixer           : on */
  text-align-last: justify;
  text-align: justify;
  font-size: 1em;
  text-justify: distribute-all-lines;
}

::-webkit-scrollbar {
  background: transparent;
  width: 12px;
  height: 4px;
}

::-webkit-scrollbar-thumb, ::-webkit-scrollbar-track {
  border-radius: 0;
  -webkit-box-shadow: none;
  box-shadow: none;
  border: 0;
}

::-webkit-scrollbar-thumb {
  background-color: #cecece;
}

::-webkit-scrollbar-thumb, ::-webkit-scrollbar-track {
  border-radius: 0;
  -webkit-box-shadow: none;
  box-shadow: none;
  border: 0;
}

.disabled {
  pointer-events: none;
  cursor: default;
  opacity: 0.5;
}

.select {
  display: inline-block;
  position: relative;
  vertical-align: middle;
  padding: 0px;
  overflow: hidden;
  background-color: #fff;
  color: #555;
  border: 1px solid #aaa;
  text-shadow: none;
  border-radius: 4px;
  transition: box-shadow 0.25s ease;
  z-index: 2;
  outline: none;
}

.select:hover {
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.15);
}

.select:before {
  content: "";
  position: absolute;
  width: 0;
  height: 0;
  border: 10px solid transparent;
  top: 14px;
  right: 10px;
  cursor: pointer;
  z-index: -2;
}

.select select {
  cursor: pointer;
  padding: 10px;
  width: 100%;
  border: none;
  background: transparent;
  background-image: none;
  -webkit-appearance: none;
  -moz-appearance: none;

}

.select select:focus {
  outline: none;
}
.viewer-prev {
  display: none !important;
}
.viewer-play{
  display: none !important;
}
.viewer-next{
  display: none !important;
}

</style>
